<template>
	<view class="">
		<uni-loading v-if="loading"></uni-loading>
		<view class="body" v-else>
			<view class="top-container">
				<view class="top-container-inner">
					<uni-list :border="false">
						<uni-list-item :border="false" title="执行者" :rightText="userInfo.name" />
						<uni-list-item :border="false" title="生产物料单编号" v-if="header.billNo"
							:rightText="header.billNo" />
						<view class="remark" v-if="type === 'create'">
							<view class="remark-title">
								备注
							</view>
							<view class="remark-textarea">
								<textarea placeholder="请输入备注" v-model="remark" />
							</view>
						</view>
					</uni-list>
				</view>
			</view>
			<!--  列表  -->
			<template v-if="materialList && materialList.length > 0">
				<view class="uni-swipe" v-for="(item, index) in materialList">
					<view class="panel">
						<view class="panel_title">
							<view class="panel_title_left">{{ item.materialName }}</view>
						</view>
						<view class="panel_content">
							<uni-list :border="false">
								<uni-list-item :border="false" title="父项物料编码" :rightText="item.materialNo" />
								<uni-list-item :border="false" title="父项物料规格" :rightText="item.materialModel" />
								<uni-list-item :border="false" title="父项物料名称" :rightText="item.childMaterialName" />
								<uni-list-item :border="false" title="子项物料编码" :rightText="item.childMaterialNo" />
								<uni-list-item :border="false" title="子项物料规格" :rightText="item.childMaterialModel" />
								<uni-list-item :border="false" title="分子" :rightText="item.numerator || '0'" />
								<uni-list-item :border="false" title="分母" :rightText="item.denominator || '0'" />
								<uni-list-item :border="false" title="应发数量" :rightText="item.count || '0'" />
								<uni-list-item :border="false" title="已领数量" :rightText="item.pickCount || '0'" />
								<uni-list-item :border="false" title="未领数量" :rightText="item.notPickCount || '0'" />
								<uni-list-item :border="false" :showArrow="!billNo" title="指定供应商"
									:rightText="item.supplierShow || (billNo ? '-' : '请选择供应商')" clickable
									@click="handleChoose('supplier', index)" />
								<uni-list-item :border="false" :showArrow="!billNo" title="指定批次"
									:rightText="item.batchNoShow || (billNo ? '-' : '请选择批次')" clickable
									@click="handleChoose('batch', index)" />
							</uni-list>
						</view>
					</view>
				</view>
			</template>
			<uni-empty-info v-else label="暂无物料清单信息"></uni-empty-info>

			<!--  底部按钮  -->
			<view class="footerPanel">
				<view class="footerPanel_body">
					<template v-if="type === 'create' && !billNo">
						<button @click="handleConfirm" class="footerBtn scan" type="primary"><i
								class="iconfont icon-duihao btn_icon"></i>完成
						</button>
					</template>
					<template v-else-if="type === 'get'">
						<button @click="handleGet" class="footerBtn scan" type="primary">领料
						</button>
					</template>
					<template v-else-if="type === 'fill'">
						<button @click="handleFill" class="footerBtn scan" type="primary">补料
						</button>
					</template>
					<template v-else-if="type === 'inStock'">
						<button @click="handleInStock" class="footerBtn scan" type="primary">扫码入库
						</button>
					</template>
				</view>
			</view>

			<!-- 级联选择 -->
			<CascadePicker class="picker-view" ref="pickerView" :popupTitle="popupInfo[currentType].popupTitle"
				:map="{text:'fName',value:'fNumber'}" @change="onchange" @datachange="ondatachange"
				@nodeclick="onnodeclick" @search="handleSearch" @scrolltolower="handleScrolltolower"
				:refresherEnabled="currentType === 'supplier'" @refresherrefresh="onRefresh" :triggered="triggered"
				:multi-select="true" :loading="pickerLoading"
				:searchPlaceholder="popupInfo[currentType].searchPlaceholder" :bottomLoading="pageConfig.pageLoading" :end="pageConfig.pageEnd">
			</CascadePicker>
		</view>
	</view>
</template>
<script>
	import uniLoading from "../../vBase/components/uni-loading/uni-loading"
	import uniEmptyInfo from "../../vBase/components/uni-empty-info/uni-empty-info"
	import CascadePicker from '../../components/cascade-picker/cascade-picker-view'
	import CascadePickerJs from '../../components/cascade-picker/cascade-picker.js'

	export default {
		components: {
			uniLoading,
			uniEmptyInfo,
			CascadePicker
		},
		mixins: [CascadePickerJs],
		data() {
			return {
				type: 'create',
				taskType: '',
				produceHouse: '',
				billNo: '',
				taskBillNo: '',
				loading: true,
				materialList: [], // 物料清单列表
				taskList: [], // 任务列表
				dataTree: [], // 组件数据
				triggered: false, // 组件下拉状态
				currentType: 'supplier', // 当前操作类型
				handleIndex: 0, // 当前操作下标
				pickerLoading: true, // 组件加载
				popupInfo: {
					supplier: {
						searchPlaceholder: '请输入供应商编码或名称',
						popupTitle: "指定供应商",
						list: []
					},
					batch: {
						searchPlaceholder: '请输入批次',
						popupTitle: "指定批次",
						list: []
					}
				},
				pageConfig: {
					pageIndex: 0,
					pageSize: 20,
					pageEnd: false,
					pageLoading: true
				},
				header: {},
				remark: "",
				isPicked: false
			}
		},
		onShow() {
			if (this.billNo) {
				this.getDataDetail()
			}
		},
		onLoad(e) {
			if (e.param) {
				// 任务列表
				this.taskList = JSON.parse(e.param)
			}
			if (e.type) this.type = e.type
			if (e.taskType) this.taskType = e.taskType
			if (e.produceHouse) this.produceHouse = e.produceHouse
			if (e.taskBillNo) this.taskBillNo = e.taskBillNo
			if (e.billNo) {
				this.billNo = e.billNo
				this.getDataDetail()
			} else {
				this.getBomList()
			}
		},
		mounted() {},
		methods: {

			/** 获取物料清单 */
			async getDataDetail() {
				try {
					const res = await this.$api.getMaterialBomDetail({
						billNo: this.billNo
					})
					if (!res.res) return
					this.materialList = res.data ?? []
					if (res.hasOwnProperty('header')) this.header = res.header ?? {}
					this.isPicked = res.picked ? res.picked : false
				} finally {
					this.loading = false
				}
			},

			/** 生成生产任务 */
			async handleConfirm() {
				try {
					Object.assign(this.taskList.dataMap, {remark: this.remark})
					uni.showLoading({
						mask: true
					})
					let res = await this.$api.createPrdTaskBill({
						taskList: this.taskList?.dataMap ?? [],
						materialList: this.materialList,
						taskType: this.taskType,
						sort: this.taskList?.dataMap?.sort ?? 0
					})
					if (!res.res) return
					uni.hideLoading()
					uni.showToast({
						title: "任务创建成功",
						icon: "none"
					})
					setTimeout(() => {
						uni.navigateBack({
							delta: 2
						});
					}, 500)
				} finally {}
			},

			/**
			 * 点击领料按钮
			 */
			handleGet() {
				if (this.isPicked) {
					uni.showToast({
						title: "此任务已领料，请走补料程序",
						icon: "none"
					})
					return
				}
				this.$navigateTo('/pages/production/taskPicking', {
					billNo: this.header?.billNo ?? '',
					taskBillNo: this.taskBillNo ?? '',
					produceHouse: this.produceHouse ?? '',
				})
			},

			/**
			 * 点击领料按钮
			 */
			handleFill() {
				this.$navigateTo('/pages/production/taskFill', {
					billNo: this.header?.billNo ?? '',
					taskBillNo: this.taskBillNo ?? '',
					produceHouse: this.produceHouse ?? '',
				})
			},

			/**
			 * 领料单入库
			 */
			handleInStock() {
				this.$navigateTo('/pages/production/taskInStork', {
					billNo: this.header?.billNo ?? '',
					taskBillNo: this.taskBillNo ?? '',
					produceHouse: this.produceHouse ?? '',
				})
			},

			/** 获取物料清单 */
			async getBomList() {
				try {
					let res = await this.$api.taskBillToMaterialList(this.taskList)
					if (!res.res) return
					this.materialList = res.materialList ?? []
				} finally {
					this.loading = false
				}
			},

			/** 获取供应商列表 */
			async getSupplierByKey() {
				try {
					let param = Object.assign({
						pageIndex: this.pageConfig.pageIndex,
						pageSize: this.pageConfig.pageSize,
					}, this.keyword ? {
						key: this.keyword
					} : {})
					let res = await this.$api.getSupplierByKey(param)
					if (!res.res) return
					if (this.pageConfig.pageIndex === 0) this.popupInfo.supplier.list = []
					if (res.data < 20) this.pageConfig.pageEnd = true
					this.popupInfo.supplier.list = this.popupInfo.supplier.list.concat(res.data ?? [])
					this.$refs.pickerView.updateData({
						treeData: this.popupInfo[this.currentType].list,
						selected: this.materialList[this.handleIndex].supplier ?? [],
						selectedIndex: 0
					})
				} finally {
					this.pickerLoading = false
					this.triggered = false
					this.pageConfig.pageLoading = false
				}
			},

			/** 获取批次 */
			async getInventoryBatch() {
				try {
					let param = Object.assign({
						pageIndex: this.pageConfig.pageIndex,
						pageSize: this.pageConfig.pageSize,
					}, this.keyword ? {
						key: this.keyword
					} : {})
					let res = await this.$api.getInventoryBatch(param)
					if (!res.res) return
					if (this.pageConfig.pageIndex === 0) this.popupInfo.batch.list = []
					if (res.data < 20) this.pageConfig.pageEnd = true
					this.popupInfo.batch.list = this.popupInfo.batch.list.concat(res.data ?? [])
					this.$refs.pickerView.updateData({
						treeData: this.popupInfo[this.currentType].list,
						selected: this.materialList[this.handleIndex].batchNo ?? [],
						selectedIndex: 0
					})
				} finally {
					this.pickerLoading = false
					this.triggered = false
					this.pageConfig.pageLoading = false
				}
			},

			/**
			 * 级联选择
			 * @param {String} e
			 * @param {Number} i
			 */
			handleChoose(e, i) {
				if (this.billNo) return
				this.keyword = null
				// 当前操作的类型
				this.currentType = e
				// 当前操作的下标
				this.handleIndex = i
				this.onRefresh()
			},
			/**
			 * 下拉
			 */
			async onRefresh(e = null) {
				this.pageConfig = {
					pageIndex: 0,
					pageSize: 20,
					pageEnd: false,
					pageLoading: true
				}
				this.triggered = true
				if (this.currentType === 'supplier') {
					await this.getSupplierByKey(e)
				} else {
					await this.getInventoryBatch(e)
				}
			},
			/**
			 * 滑动到底部
			 */
			async handleScrolltolower() {
				if (this.currentType === 'batch') return
				if (this.pageConfig.pageEnd || this.pageConfig.pageLoading) return
				this.pageConfig.pageLoading = true
				this.pageConfig.pageIndex++
				if (this.currentType === 'supplier') {
					await this.getSupplierByKey()
				} else {
					await this.getInventoryBatch()
				}
			},
			onchange(e) {
				if (this.currentType === 'supplier') {
					this.materialList[this.handleIndex] = Object.assign(this.materialList[this.handleIndex], {
						supplierShow: e.map(option => option.fName).join('，'),
						supplier: e
					})
				} else {
					this.materialList[this.handleIndex] = Object.assign(this.materialList[this.handleIndex], {
						batchNoShow: e.map(option => option).join('，'),
						batchNo: e
					})
				}
				this.$forceUpdate()
			},
			/**
			 * 组件查询
			 * @param {Object} e
			 */
			handleSearch(e) {
				this.keyword = e
				this.pageConfig = {
					pageIndex: 0,
					pageSize: 20,
					pageEnd: false,
					pageLoading: true
				}
				if (this.currentType === 'supplier') {
					this.getSupplierByKey()
				} else {
					this.getInventoryBatch()
				}
			},
			onnodeclick(e) {},
			onpopupopened(e) {},
			onpopupclosed(e) {},
		}
	}
</script>
<style lang="scss" scoped>
	@import "../../static/css/common";

	.panel_content {
		::v-deep.uni-list-item__container {
			padding: 8px 0;

			.uni-list-item__content {
				min-width: 100px;
				flex: none;
			}

			.uni-list-item__extra {
				flex: 1;

				.uni-list-item__extra-text {
					font-size: 14px;
				}
			}

		}

		::v-deep.uni-icon-wrapper {
			padding: 0;
		}
	}

	.footerBtn {
		margin: 0 !important;
	}
	
	.remark {
		padding: 12px 15px;
		display: flex;
		
		.remark-title {
			font-size: 14px;
			color: #3b4144;
			margin-right: 32px;
		}
		
		.remark-textarea {
			flex: 1;
			height: 70px;
			box-sizing: border-box;
			// padding: 10px 0;
			
			uni-textarea {
				border: 1px solid #e2e2e2;
				box-sizing: border-box;
				padding: 8px;
				border-radius: 8px;
				height: 100%;
				width: 100%;
				font-size: 12px;
				color: #999999;
			}
		}
	}
</style>
